'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 建筑
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var Code = require('../consts/code');
var moduleType = require('../consts/moduleType');
var operationType = require('../consts/operationType');
var unionBossConf = require('../config/unionBossConf.js');
var rewardService = require('./rewardService.js');
var genRewardService = require('./genRewardService.js');
var mailService = require('./mailService.js');
var PlayerManager = require('../libs/playerManager.js');
var langUtil = require('../util/langUtil');

/**
 * 发放伤害排行奖励
 * @return {[type]}             [description]
 */
exports.doDamageRankReward = function (union_boss_model, callback) {
    var boss_id = union_boss_model.curr_boss_id;
    var dmg_list = [];
    _.forEach(union_boss_model.damage_list, function (dmg_info) {
        dmg_list.push({
            role_id: dmg_info.role_id,
            damage: dmg_info.damage,
            last_modify_tm: dmg_info.last_modify_tm
        });
    });
    _.orderBy(dmg_list, ['damage', 'last_modify_tm'], ['desc', 'asc']);
    var rank = 0;
    async.eachSeries(dmg_list, function (dmg, cb1) {
        rank++;
        var role_id = dmg.role_id;
        var player_manager = new PlayerManager(role_id);
        async.waterfall(
            [
                function (cb) {
                    player_manager.getModel(['mail'], cb);
                },
                function (cb) {
                    _sendRankRewardMail(player_manager.mail, boss_id, rank);
                    player_manager.save(cb);
                }
            ],
            function (err) {
                cb1();
            }
        );
    }, function (err) {
        callback();
    });
};

/**
 * 发放奖励邮件
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
var _sendRankRewardMail = function (mail_model, boss_id, rank) {
    var reward_conf = unionBossConf.getRankRewardInfo(rank);
    if (!reward_conf) {
        console.error('发放联盟BOSS伤害排行奖励失败，排名无效:' + rank);
        return false;
    }
    var reward_list = genRewardService.generateRewardList(reward_conf);

    var boss_conf = unionBossConf.getUnionBossConf(boss_id);
    var boss_name = boss_conf.name;

    var title = langUtil.getString('union_boss_damage_rank_mail_title');
    var content = langUtil.getString('union_boss_damage_rank_mail_content');
    title = title.replace(/{BOSS_NAME}/g, boss_name);
    title = title.replace(/{RANK}/g, rank);
    content = content.replace(/{BOSS_NAME}/g, boss_name);
    content = content.replace(/{RANK}/g, rank);

    var module_type = moduleType.MDL_UNION_BOSS;
    var operation_type = operationType.OPR_UNION_BOSS_LAST_KILL_REWARD;
    var res_int_val = boss_id;
    var res_str_val = rank;

    mailService.sendMail(mail_model, title, content, reward_list, module_type, operation_type, res_int_val);
};
